#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020-03-11 14:08:00
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：

# -*-coding:utf-8-*-
import stomp
import time_ext_
import timeEXT
import re
import os
from queue import Queue
import logging


log = logging.getLogger('main.AMQ')
# 存储接收数据队列
receive_queue = Queue()
# 存储报文路径
pathList = ['./data/xml/send', './data/xml/receive']


def mkdir():
    for path in pathList:
        try:
            os.makedirs(path, 0o777)
            log.warning('创建报文存储文件夹：{}'.format(path))
        except:
            pass
# 创建存储目录
mkdir()

# 存储数据


def save_data(msg, path):
    with open(path, 'w+', encoding='utf-8') as f:
        f.write(msg)
        log.warning("报文已存储到：{}".format(path))
        return True

# 消费者数据处理


class SampleListener(object):

    def on_message(self, headers, msg):
        log.warning(
            '接收来自队列：{},消息-->:\n**********\n{}\n**********\n'.format(headers['destination'], msg))
        receive_queue.put(msg)
        filePath = "{}/receive_{}.xml".format(
            pathList[1], timeEXT.DatetimeStrToNumber(timeEXT.GetDatetimeStr()))
        save_data(msg, filePath)
# 队列模式


class Amq_Queue_Client(object):
    """docstring for Amq_queue_client"""
    connect = None

    def __init__(self, host='127.0.0.1', port=61613, send_listener='/queue/icstocics', receive_listener='/queue/cicstoics',mode='queue'):
        super(Amq_Queue_Client, self).__init__()
        self.log = log
        self.host = host
        self.port = port
        self.send_listener = send_listener
        self.receive_listener = receive_listener
        self.mode=mode
        self.get_mode()
        self.connect = self.init_connect()
        self.receive_from_queue()
    #模式
    def get_mode(self):
        send_modeStr = re.findall('\w+$',self.send_listener)[0]
        receive_modeStr = re.findall('\w+$',self.receive_listener)[0]
        if self.mode=='queue':
            self.send_listener="/queue/{}".format(send_modeStr)
            self.receive_listener="/queue/{}".format(receive_modeStr)
        elif self.mode=='topic':
            self.send_listener="/topic/{}".format(send_modeStr)
            self.receive_listener="/topic/{}".format(receive_modeStr)
    # 初始AMQ连接
    def init_connect(self):
        if not self.connect:
            self.log.warning("连接到AMQ服务,{}:{} 成功".format(self.host, self.port))
            return stomp.Connection10([(self.host, self.port)])
        else:
            return self.connect
    # 发送消息到AMQ

    def send_to_queue(self, msg):
        try:
            self.connect.start()
            self.connect.connect()
            self.connect.send(self.send_listener, msg)
            self.log.warning(
                "发送消息,队列：{}，消息-->:\n**********\n{}\n**********\n".format(self.send_listener, msg))
            filePath = "{}/send_{}.xml".format(
                pathList[0], timeEXT.DatetimeStrToNumber(timeEXT.GetDatetimeStr()))
            save_data(msg, filePath)
            return True
        except Exception as e:
            self.log.debug("发送数据失败,{}".format(e))
            return False

    def receive_from_queue(self):
        self.connect.set_listener(self.receive_listener, SampleListener())
        self.connect.start()
        self.connect.connect()
        self.connect.subscribe(self.receive_listener)
        time_ext_.sleep(1)  # secs
    # 获取接收数据

    def get_receive_msg(self, receive_queue=receive_queue):
        if receive_queue.qsize() > 0:
            msg = receive_queue.get()
            # self.log.warning("接收数据-->：\n**********\n{}\n**********\n".format(msg))
            return msg
        else:
            self.log.warning('没有接收到新数据')
    # 关闭

    def close(self):
        res = self.connect.disconnect()
        self.log.warning('断开AQM连接：{}'.format(res))

if __name__ == '__main__':
    amq=Amq_Queue_Client(mode='topic')
    while 1:

        amq.send_to_queue(str(time_ext_.time()))
        xx=amq.get_receive_msg()
        # print(1111111111,xx)

        time_ext_.sleep(10)
